package com.mtons.mblog.modules.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.mtons.mblog.base.utils.BeanUtils;
import com.mtons.mblog.modules.data.Archive;
import com.mtons.mblog.modules.data.PostVO;
import com.mtons.mblog.modules.entity.Post;
import com.mtons.mblog.modules.repository.PostRepository;
import com.mtons.mblog.modules.service.ArchiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * HistoryServiceImpl.
 * @author yuzhong
 * @date 2019/2/22 11:22
 */
@Service
public class ArchiveServiceImpl implements ArchiveService {

    @Autowired
    private PostRepository postRepository;

    private Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC, "created"));

    @Override
    public Map<Date, List<PostVO>> findAll() {
        List<Post> posts = postRepository.findAll(sort);
        Map<Date, List<Post>> collect = posts.stream().collect(
                Collectors.groupingBy(item ->
                    item.getCreated()
                ));
        Map<Date, List<PostVO>> archives = BeanUtils.copyProperties(collect,
                                                                    new TypeReference<Map<Date, List<PostVO>>>() {
                                                                    });
        return archives;

    }

    /**
     * 查询归档信息 根据年份和月份
     *
     * @return List
     */
    @Override
    public List<Archive> findPostGroupByYearAndMonth() {
        //把归档数据查询出来，不包含文章数据
        List<Object[]> objects = postRepository.findPostGroupByYearAndMonth();
        //Archive的集合
        List<Archive> archives = new ArrayList<>();
        Archive archive = null;
        //遍历objects集合，分别根据年份月份查询出对应的文章，保存在archive实体，最后在循环结束时将archive添加到archives集合。
        for (Object[] obj : objects) {
            archive = new Archive();
            archive.setYear(obj[0].toString());
            archive.setMonth(obj[1].toString());
            archive.setCount(Integer.parseInt(obj[2].toString()));
            archive.setPosts(this.findPostByYearAndMonth(obj[0].toString(), obj[1].toString()));
            archives.add(archive);
        }
        return archives;
    }

    /**
     * 根据年份和月份查询文章
     *
     * @param year  year
     * @param month month
     * @return list
     */
    @Override
    public List<Post> findPostByYearAndMonth(String year, String month) {
        return postRepository.findPostByYearAndMonth(year, month);
    }




}
